package com.jader.fragment;
/*商家详情页*/
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import me.maxwin.view.XListView;
import me.maxwin.view.XListView.IXListViewListener;

import org.json.JSONArray;
import org.json.JSONObject;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jader.adapter.MerchantAdapter;
import com.jader.beans.Goods;
import com.jader.beans.Seller_detail;
import com.jader.myviews.MyProgressDialog;
import com.jader.util.JaderApplication;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.zlp.jader.R;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class Store_Goods_fragment extends Fragment implements
		IXListViewListener, OnClickListener {
	private View view;
	private XListView merchantListView;
	private RequestQueue queue;
	private MerchantAdapter adapter;
	private List<Goods> list = new ArrayList<Goods>();
	private JaderApplication application;
	private JsonArrayRequest arrayRequest;
	private String url = JaderApplication.getIP() + "/Jader/client?type="
			+ JaderApplication.SELLER_GOODSBYID + "&page=";
	private String url1 = JaderApplication.getIP() + "/Jader/client?type="
			+ JaderApplication.SELLER_DETAIL + "&sellerid=";
	private int page = 0;
	private int result;
	private String time = null;
	private RadioGroup group;
	private RadioButton priceButton;
	private boolean flag = true;
	private int classification = 1;
	private int sellerid;
	private Activity activity;
	private ImageView seller_picture, store_back, store_user_picture;
	private TextView store_title, store_followers_count;
	private BitmapUtils bitmapUtils;
	private Seller_detail seller_detail;
	private JsonObjectRequest objectRequest;
	private int seller_count;
	private CheckBox sc_check;
	private MyProgressDialog dialog;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		this.activity = activity;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.store_goods_fragment_layout,
				container, false);
		initViews();
		return view;
	}

	@Override
	public void onResume() {

		application = (JaderApplication) getActivity().getApplication();
		sellerid = getActivity().getIntent().getIntExtra("sellerid", 0);
		bitmapUtils = JaderApplication.getBitmapUtils();
		queue = application.getQueue();
		sendRequest(url1 + sellerid);
		super.onResume();
	}

	private void initData() {
		adapter = new MerchantAdapter(list, getActivity());
		merchantListView.setAdapter(adapter);
		sendReques(url + page + "&sellerid=" + sellerid + "&classification="
				+ classification);
		Log.e("error", url + page + "&sellerid=" + sellerid
				+ "&classification=" + classification);
		merchantListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				int position = arg2 - 2;
				if (position >= 0 && position <= list.size()) {
					Intent intent = new Intent(getActivity(),
							com.jader.activities.Seller.class);
					intent.putExtra("goods", list.get(position));
					intent.putExtra("sellerid", sellerid);
					startActivity(intent);
				}

			}
		});
	}

	private void initViews() {
		merchantListView = (XListView) view.findViewById(R.id.store_list);
		View head = View.inflate(getActivity(), R.layout.activity_store, null);
		merchantListView.addHeaderView(head);
		seller_picture = (ImageView) head.findViewById(R.id.seller_picture);
		store_back = (ImageView) head.findViewById(R.id.store_back);
		store_user_picture = (ImageView) head.findViewById(R.id.store_image);
		store_title = (TextView) head.findViewById(R.id.store_title);
		store_followers_count = (TextView) head
				.findViewById(R.id.store_followers_count);

		store_back.setOnClickListener(this);
		group = (RadioGroup) head.findViewById(R.id.store_choice_layout);
		priceButton = (RadioButton) head.findViewById(R.id.store_price);
		merchantListView.setPullLoadEnable(true);
		merchantListView.setXListViewListener(this);
		application = (JaderApplication) getActivity().getApplication();
		queue = application.getQueue();
		sc_check = (CheckBox) head.findViewById(R.id.store_sc);
		priceButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				boolean isChecked = priceButton.isChecked();
				if (isChecked) {
					if (flag) {
						priceButton.setText("价格最高");
						classification = 3;
						list.clear();
						result = 0;
						page = 0;
						sendReques(url + page + "&sellerid=" + sellerid
								+ "&classification=" + classification);
						flag = false;
					} else {
						priceButton.setText("价格最低");
						classification = 4;
						list.clear();
						result = 0;
						page = 0;
						sendReques(url + page + "&sellerid=" + sellerid
								+ "&classification=" + classification);
						flag = true;
					}
				}
			}
		});
		group.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup arg0, int arg1) {
				switch (arg1) {
				case R.id.store_new_release:
					classification = 1;
					result = 0;
					page = 0;
					list.clear();
					sendReques(url + page + "&sellerid=" + sellerid
							+ "&classification=" + classification);
					break;
				case R.id.store_popularity:
					classification = 2;
					result = 0;
					page = 0;
					list.clear();
					sendReques(url + page + "&sellerid=" + sellerid
							+ "&classification=" + classification);
					break;
				default:
					break;
				}

			}
		});
	}

	private void onLoad() {
		merchantListView.stopRefresh();
		merchantListView.stopLoadMore();
		if (time == null) {
			merchantListView.setRefreshTime("刚刚");
		} else {
			merchantListView.setRefreshTime(time);
		}
		Date date = new Date();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		time = df.format(date);
	}

	@Override
	public void onRefresh() {
		result = 0;
		page = 0;
		sendReques(url + page + "&sellerid=" + sellerid + "&classification="
				+ classification);
	}

	@Override
	public void onLoadMore() {
		page = list.size();
		result = list.size();
		sendReques(url + page + "&sellerid=" + sellerid + "&classification="
				+ classification);
	}

	private void sendReques(String url) {
		arrayRequest = new JsonArrayRequest(url,
				new Response.Listener<JSONArray>() {

					@Override
					public void onResponse(JSONArray response) {
						onLoad();
						Gson gson = new Gson();
						// TypeToken内的泛型就是Json数据中的类型
						Type listType = new TypeToken<ArrayList<Goods>>() {
						}.getType();
						List<Goods> arrayList = gson.fromJson(
								response.toString(), listType);
						for (Goods user : arrayList) {
							boolean flag = true;
							for (Goods user2 : list) {
								if (user.equals(user2)) {
									flag = false;
								}
							}
							if (flag) {
								list.add(result, user);
								result++;
							}
						}
						adapter.notifyDataSetChanged();
					}

				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						onLoad();
					}
				});
		queue.add(arrayRequest);
	}

	private void sendRequest(String url) {
		dialog = JaderApplication.getMyDialog(activity);
		if (JaderApplication.user != null) {
			url = url + "&userid=" + JaderApplication.user.getUserid();
		}
		objectRequest = new JsonObjectRequest(url, null,
				new Response.Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject response) {
						Gson gson = new Gson();
						seller_detail = gson.fromJson(response.toString(),
								Seller_detail.class);
						getData();
						initData();
						if (dialog.isShowing()) {
							dialog.dismiss();
						}
					}

				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						if (dialog.isShowing()) {
							dialog.dismiss();
						}
					}
				});
		dialog.show();
		queue.add(objectRequest);

	}

	private void getData() {
		Log.e("商品图片详情",JaderApplication.getIP()
				+ seller_detail.getSeller().getPicture());
		bitmapUtils.display(seller_picture, JaderApplication.getIP()
			+"/Jader"+ seller_detail.getSeller().getPicture());
		bitmapUtils.display(store_user_picture, JaderApplication.getIP()
				+"/Jader"+ seller_detail.getUser_picture());
		store_title.setText(seller_detail.getSeller().getSellername());
		seller_count = seller_detail.getCount();
		store_followers_count.setText(seller_count + "");
		boolean flag = seller_detail.isCollect();
		sc_check.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (sc_check.isChecked()) {
					collect_goods();
				} else {
					cancel_collect_goods();
					sc_check.setBackgroundResource(R.color.jader_theme);
					sc_check.setText(R.string.store_sc);
					seller_count--;
					store_followers_count.setText(seller_count + "");
				}

			}
		});
		if (flag) {
			sc_check.setChecked(true);
			sc_check.setBackgroundResource(R.color.white_f);
			sc_check.setText(R.string.store_ysc);
		}

	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.store_back:
			getActivity().finish();
			break;

		default:
			break;
		}

	}

	private void collect_goods() {
		if (JaderApplication.user == null) {
			sc_check.setChecked(false);
			sc_check.setBackgroundResource(R.color.jader_theme);
			sc_check.setText(R.string.store_sc);
			store_followers_count.setText(seller_count + "");
			JaderApplication.login(activity);
			return;
		} else {
			sc_check.setBackgroundResource(R.color.white_f);
			sc_check.setText(R.string.store_ysc);
			seller_count++;
			store_followers_count.setText(seller_count + "");
			String url = JaderApplication.getIP() + "/Jader/client?type="
					+ JaderApplication.COLLECTID_SELLER + "&userid="
					+ JaderApplication.user.getUserid() + "&sellerid="
					+ seller_detail.getSeller().getSellerid();
			HttpUtils httpUtils = new HttpUtils();
			httpUtils.configCurrentHttpCacheExpiry(10 * 0);
			dialog.show();
			httpUtils.send(HttpMethod.GET, url, new RequestCallBack<String>() {

				@Override
				public void onFailure(HttpException arg0, String arg1) {
					sc_check.setChecked(false);
					sc_check.setBackgroundResource(R.color.jader_theme);
					sc_check.setText(R.string.store_sc);
					seller_count--;
					store_followers_count.setText(seller_count + "");
					JaderApplication.show(activity, "访问网络失败");
					if (dialog.isShowing()) {
						dialog.dismiss();
					}

				}

				@Override
				public void onSuccess(ResponseInfo<String> arg0) {
					String result = arg0.result;
					boolean flag = false;
					if (result != null && !"".equals(result)) {
						flag = Boolean.parseBoolean(result);
					}
					if (flag) {
						sc_check.setChecked(flag);
						sc_check.setBackgroundResource(R.color.white_f);
						sc_check.setText(R.string.store_ysc);
					} else {
						sc_check.setChecked(!flag);
						sc_check.setBackgroundResource(R.color.jader_theme);
						sc_check.setText(R.string.store_sc);
						seller_count--;
						store_followers_count.setText(seller_count + "");
						JaderApplication.show(activity, "操作失败，请重试");
					}
					if (dialog.isShowing()) {
						dialog.dismiss();
					}
				}
			});
		}
	}

	private void cancel_collect_goods() {
		String url = JaderApplication.getIP() + "/Jader/client?type="
				+ JaderApplication.CANCEL_COLLECTID_SELLER + "&userid="
				+ JaderApplication.user.getUserid() + "&sellerid="
				+ seller_detail.getSeller().getSellerid();
		HttpUtils httpUtils = new HttpUtils();
		httpUtils.configCurrentHttpCacheExpiry(10 * 0);
		dialog.show();
		httpUtils.send(HttpMethod.GET, url, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				sc_check.setChecked(true);
				sc_check.setBackgroundResource(R.color.white_f);
				sc_check.setText(R.string.store_ysc);
				seller_count++;
				store_followers_count.setText(seller_count + "");
				JaderApplication.show(activity, "访问网络失败");
				if (dialog.isShowing()) {
					dialog.dismiss();
				}

			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				String result = arg0.result;
				boolean flag = false;
				if (result != null && !"".equals(result)) {
					flag = Boolean.parseBoolean(result);
				}
				if (flag) {
					sc_check.setChecked(!flag);
					sc_check.setBackgroundResource(R.color.jader_theme);
					sc_check.setText(R.string.store_sc);
				} else {
					sc_check.setChecked(flag);
					sc_check.setBackgroundResource(R.color.white_f);
					sc_check.setText(R.string.store_ysc);
					seller_count++;
					store_followers_count.setText(seller_count + "");
					JaderApplication.show(activity, "操作失败，请重试");
				}
				if (dialog.isShowing()) {
					dialog.dismiss();
				}
			}
		});

	}
}
